const chalk = require('chalk');
const expressJwt = require('express-jwt');
const fs = require('fs');
const path = require('path');
const config = require('../config');
const logger = require('./_logger');
const db = require('../models');
const getIp = require('./utils.ip');
const activeLogFilePath = path.resolve(process.cwd(), 'logs/operation_logs_active.log');


/**
 * token验证函数
 *
 * @param  {[type]}   req  请求对象
 * @param  {[type]}   res  响应对象
 * @param  {Function} next 传递事件函数
 */
exports.tokenAuth = expressJwt({
    secret: config.jwtSecretKey,
    algorithms: ['HS256'],
    credentialsRequired: true, //对没有携带token的 接口也抛出错误
})

/**
 * 权限验证函数
 * @param  {[type]}   req  请求对象
 * @param  {[type]}   res  响应对象
 */
exports.permissionAuth = async (req, res, next) => {
    const startTime = Date.now();
    req.ip_data = await getIp(req);
    const sessionId = req.headers["visitor-id"];
    if (!req.user?.connectSid) {
        logger.warnLog("权限验证====>没有用户信息 ");
        return res.sendResultAto(null, 4, "请登录");
    }
    db.redis.get(`${req.user?.connectSid}:${sessionId}:token`, (err, obj) => {
        if (err || !obj) {
            logger.warnLog(`权限验证==> ${req.user?.connectSid}:${sessionId}:token ==>token:${obj}==>err:${err}`);
            return res.sendResultAto(null, 4, "请登录");
        }
        // 保存原始的 res.send 方法
        const originalSend = res.send;
        res.send = function (body) {
            res._response_body = body; // 捕获响应体
            originalSend.call(this, body); // 调用原始的 res.send 方法发送响应
        };
        // 监听请求结束事件
        res.on('finish', async () => {
            const response_body = JSON.parse(res._response_body || '{}');
            let status = false;
            // response_body.meta?.status   -1:失败 0,1:成功 4:未登录
            if (![500, 404, 304].includes(res.statusCode) && response_body.meta?.status >= 0 && response_body.meta?.status != 4) {
                status = true;
            }
            const log = {
                status,
                user_id: req.user.id,
                api_path: req.originalUrl,
                method: req.method,
                request_headers: req.headers,
                request_body: req.body || req.query || req.params || {},
                response_headers: res.getHeaders(),
                response_body,
                ip_address: req.ip_data.ip,
                location: req.ip_data.address,
                os: req.ip_data.system,
                browser: req.ip_data.browser,
                duration: Date.now() - startTime,
                request_time: new Date(),
            }
            // 确保日志文件存在，不存在则创建
            if (!fs.existsSync(activeLogFilePath)) {
                fs.writeFileSync(activeLogFilePath, '');
            }
            // 追加到日志文件中
            fs.appendFile(activeLogFilePath, JSON.stringify(log) + '\n', (err) => {
                if (err) {
                    logger.errLog(`操作日志记录失败==>${err}`);
                }
            });

        })
        next();
    })
}